<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入标题关键词"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter="handleFilter"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button class="filter-item" type="primary" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="success" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增作品
      </el-button>
    </div>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="title"
        label="标题"
        min-width="150"
      />
      <el-table-column
        prop="coverImage"
        label="封面图"
        width="180"
      >
        <template #default="scope">
          <el-image
            :src="getServerUrl() + scope.row.coverImage"
            style="width: 100px; height: 60px"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="views"
        label="浏览量"
        width="100"
        align="center"
      />
      <el-table-column
        prop="comments"
        label="评论数"
        width="100"
        align="center"
      />
      <el-table-column
        prop="createTime"
        label="发布时间"
        width="180"
        align="center"
      >
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="listQuery.pageNum"
      v-model:limit="listQuery.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增作品' : '编辑作品'"
      v-model="dialogFormVisible"
      width="650px"
    >
      <el-form
        ref="dataFormRef"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="temp.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="avatar-uploader"
            :action="getServerUrl() + '/admin/note/uploadImage'"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            只能上传jpg/png格式图片，且不超过2MB
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Picture } from '@element-plus/icons-vue'
import  axios from '@/util/axios'
import { getServerUrl } from '@/config/sys'
import Pagination from '@/components/Pagination'

const list = ref([])
const total = ref(0)
const listLoading = ref(false)
const dialogFormVisible = ref(false)
const dialogStatus = ref('create')
const dataFormRef = ref(null)
const imageUrl = ref('')

const listQuery = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

const temp = ref({
  id: undefined,
  title: '',
  description: '',
  coverImage: ''
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  coverImage: [{ required: true, message: '请上传封面图', trigger: 'change' }]
}

const headers = {
  Authorization: localStorage.getItem('token')
}

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const url = 'portfolio/list';
    const params = listQuery.value;
    // 手动拼接参数到URL上
    let queryString = '';
    for (const key in params) {
      if (params.hasOwnProperty(key)) {
        if (queryString.length > 0) {
          queryString += '&';
        }
        queryString += `${key}=${params[key]}`;
      }
    }
    const fullUrl = `${url}?${queryString}`;
    console.log("fullUrl", fullUrl)
    // const { data } = await axios.get('portfolio/list', { params: listQuery.value })
    const { data } = await axios.get(fullUrl)
    list.value = data.data.records
    total.value = data.data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleFilter = () => {
  listQuery.value.pageNum = 1
  getList()
}

// 重置表单
const resetTemp = () => {
  temp.value = {
    id: undefined,
    title: '',
    description: '',
    coverImage: ''
  }
  imageUrl.value = ''
}

// 新增
const handleCreate = () => {
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}

// 编辑
const handleEdit = (row) => {
  temp.value = Object.assign({}, row)
  imageUrl.value = getServerUrl() + row.coverImage
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}

// 创建数据
const createData = () => {
  dataFormRef.value?.validate(async(valid) => {
    if (valid) {
      try {
        const { data } = await axios.post('portfolio/add', temp.value)
        if (data.code === 0) {
          dialogFormVisible.value = false
          ElMessage.success('创建成功')
          getList()
        } else {
          ElMessage.error(data.msg || '创建失败')
        }
      } catch (error) {
        console.error('创建失败:', error)
        ElMessage.error('创建失败')
      }
    }
  })
}

// 更新数据
const updateData = () => {
  dataFormRef.value?.validate(async(valid) => {
    if (valid) {
      try {
        const { data } = await axios.post('portfolio/update', temp.value)
        if (data.code === 0) {
          dialogFormVisible.value = false
          ElMessage.success('更新成功')
          getList()
        } else {
          ElMessage.error(data.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该作品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    try {
      const { data } = await axios.post(`portfolio/delete/${row.id}`)
      if (data.code === 0) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(data.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 图片上传前的验证
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功的回调
const handleImageSuccess = (response) => {
  if (response.code === 0) {
    imageUrl.value = getServerUrl() + response.data.src
    temp.value.coverImage = response.data.src
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 格式化时间
const formatDateTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.filter-container {
  padding-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style> 